<template>
  <div class="regulatory-page">
    <div class="return" @click="goBack">
      <Icon size="25" color="#000000" name="arrow-left" class="back" />
      <div class="title">
        <p class="text">订单信息</p>
      </div>
    </div>
    <div class="address-display" @click="showAddressModal">
      <p v-if="chosenAddress" class="first-line">
        {{ chosenAddress.region }}
        <span v-if="chosenAddress.isDefault" class="default-tag">默认</span>
      </p>
      <p v-if="chosenAddress" class="second-line">
        {{ chosenAddress.addressLine }}
        <Icon size="20" color="#999987" name="arrow" class="arrow-right" />
      </p>
      <p v-if="chosenAddress" class="third-line">{{ chosenAddress.name }} {{ chosenAddress.contact }}</p>
      <p v-else>请选择收货地址</p>
    </div>
    <div class="info-display" v-for="(item, index) in orderItems" :key="index">
      <van-card
          :price="item.itemPrice.toFixed(2)"
          :desc="item.description"
          :title="item.title"
          :thumb="item.thumbnail"
          class="van-card-full"
      >
        <template #tags>
          <van-tag plain type="danger">七天无理由</van-tag>
        </template>
        <template #footer>
          <van-stepper v-model="item.skuQuantity" integer :max="item.max"/>
        </template>
      </van-card>
      <div class="divider"></div>
      <div class="delivery-display">
        <div class="common-display" @click="showDeliveryModal">
          <p class="left-text">配送方式</p>
          <p class="right-text">{{ deliveryMethodText }}<Icon size="14" color="#808080" name="arrow" /></p>
        </div>
        <div class="common-display">
          <p class="left-text">配送时间</p>
          <p class="right-text">现在支付，预计2天左右送达</p>
        </div>
      </div>
    </div>
    <div class="price-display">
      <div class="common-display">
        <p class="left-text">商品总价</p>
        <p class="right-text">¥ {{ totalPrice.toFixed(2) }}</p>
      </div>
      <div class="common-display">
        <p class="left-text">快递费用</p>
        <p class="right-text">¥ {{ deliveryFee }}</p>
      </div>
      <div class="divider"></div>
      <div class="total-account">
        <span>小计：<span class="total-price">{{ (totalPrice + deliveryFee).toFixed(2) }} </span>元</span>
      </div>
    </div>
    <div class="coupons-display">
      <van-coupon-cell
          :coupons="coupons"
          :chosen-coupon="chosenCoupon"
          @click="showList = true"
      />
      <van-popup
          v-model="showList"
          round
          position="bottom"
          style="height: 90%; padding-top: 4px;"
      >
        <van-coupon-list
            :coupons="coupons"
            :chosen-coupon="chosenCoupon"
            :disabled-coupons="disabledCoupons"
            @change="onChange"
            :show-exchange-bar="false"
        />
      </van-popup>
    </div>
    <div class="pay-display">
      <div class="common-display">
        <p class="pay-text"><Icon color="#5A9EF7" name="alipay" size="18" class="pay-icon"/>支付宝支付</p>
        <p class="right-text">
          <van-radio v-model="paymentMethod" name="alipay" checked-color="#FA6408" icon-size="15px"/>
        </p>
      </div>
      <div class="common-display">
        <p class="pay-text"><Icon color="#50B674" name="wechat" size="18" class="pay-icon"/>微信支付</p>
        <p class="right-text">
          <van-radio v-model="paymentMethod" name="wechat" checked-color="#FA6408" icon-size="15px"/>
        </p>
      </div>
    </div>
    <van-submit-bar :price="(totalPrice + deliveryFee) * 100" button-text="提交订单" @submit="onSubmit" :label="'共' + skuQuantity + '件   合计：'" />

    <van-popup v-model="showModal" position="bottom" :style="{ height: '80%' }">
      <AddressView @select-address-id="selectAddressById" :from-order="true" />
    </van-popup>

    <van-popup v-model="showDeliveryModalPopup" position="bottom" :style="{ height: '20%' }">
      <div class="delivery-options">
        <div @click="selectDeliveryMethod('standard')" class="delivery-option">普通快递，免配送费</div>
        <div @click="selectDeliveryMethod('express')" class="delivery-option">加急快递，配送费¥5</div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {
  Icon,
  SubmitBar as VanSubmitBar,
  Popup as VanPopup,
  Card as VanCard,
  Tag as VanTag,
  Radio as VanRadio,
  Stepper as VanStepper, Dialog, Toast,CouponCell as VanCouponCell, CouponList as VanCouponList
} from "vant";
import AddressView from "@/views/common-views/my-views/AddressView";
import http from "@/plugins/http";

export default {
  name: "OrderView",
  components: { Icon, VanSubmitBar, VanPopup, AddressView, VanCard, VanTag, VanRadio, VanStepper,VanCouponCell,VanCouponList },
  data() {
    return {
      chosenAddress: null,
      orderItems: [],
      orderData: [],
      showModal: false,
      showDeliveryModalPopup: false,
      paymentMethod: 'alipay',
      skuQuantity: 0,
      itemPrice: 0,
      description: "",
      title: "",
      thumbnail: "",
      deliveryMethod: 'standard',
      max: 0,
      productId: 0,
      AddressId: 0,
      orderId: "",
      chosenCoupon: -1,
      coupons: [],
      disabledCoupons: [],
      showList: false,
    };
  },
  computed: {
    subtotal() {
      return this.orderItems.reduce((sum, item) => {
        return sum + (item.itemPrice * item.skuQuantity);
      }, 0);
    },
    couponDiscount() {
      if (this.chosenCoupon !== -1 && this.coupons[this.chosenCoupon]) {
        return this.coupons[this.chosenCoupon].value/100;
      }
      return 0;
    },
    totalPrice() {
      return Math.max(0, this.subtotal - this.couponDiscount);
    },
    deliveryFee() {
      return this.deliveryMethod === 'express' ? 5 : 0;
    },
    deliveryMethodText() {
      return this.deliveryMethod === 'express' ? '加急快递，运费 ¥ 5' : '普通快递，免配送费';
    },
    applicableCoupons() {
      return this.coupons.filter(coupon => {
        const requiredAmount = parseFloat(coupon.condition.match(/\d+/)[0]);
        return this.totalPrice >= requiredAmount;
      });
    }
  },
  activated() {
    this.orderData = this.$route.params.orderData;
    this.orderItems = this.orderData.map(item => ({
      cartId: item.cartId,
      productName: item.productName,
      description: item.skuDescription,
      itemPrice: item.price,
      skuQuantity: item.quantity,
      title: item.productName,
      thumbnail: item.imgUrl,
      max: item.stock_num,
      productId: item.productId,
    }));
    this.fetchDefaultAddress();
    this.fetchCoupons();
    this.updateChosenAddressFromRoute();
  },
  watch: {
    '$route.query.chosenAddressId': 'updateChosenAddressFromRoute'
  },
  methods: {
    fetchCoupons() {
      const username = JSON.parse(sessionStorage.getItem('username'));
      if (username) {
        http.get(`/coupon/user/${username}`)
            .then(response => {
              const fetchedCoupons = response.data;
              if (fetchedCoupons && Array.isArray(fetchedCoupons)) {
                const allCoupons = fetchedCoupons.map(coupon => ({
                  id: coupon.couponId,
                  name: coupon.name,
                  condition: `满${coupon.condition}可用`,
                  value: parseFloat(coupon.count*100),
                  startAt: new Date(coupon.createTime).getTime() / 1000,
                  endAt: new Date(coupon.endTime).getTime() / 1000,
                  valueDesc: coupon.count.toString(),
                  unitDesc: '元',
                  available: 1
                }));

                this.coupons = allCoupons.filter(coupon => {
                  const conditionValue = parseFloat(coupon.condition.match(/\d+/)[0]);
                  return this.subtotal >= conditionValue;
                });

                this.disabledCoupons = allCoupons.filter(coupon => {
                  const conditionValue = parseFloat(coupon.condition.match(/\d+/)[0]);
                  return this.subtotal < conditionValue;
                });
              }
            })
            .catch(error => {
              console.error("获取优惠券信息出错:", error);
            });
      } else {
        console.error("没有用户登录");
      }
    },
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
      if (index !== -1) {
        const selectedCoupon = this.coupons[index];
        console.log(`选择了优惠券: ${selectedCoupon.name}, 价值: ${selectedCoupon.valueDesc}${selectedCoupon.unitDesc}`);
        Toast.success(`已应用优惠券，订单总价已更新`);
      } else {
        Toast.info('已取消使用优惠券');
      }
    },
    goBack() {
      Dialog.confirm({
        title: '确认返回',
        message: '订单还未支付',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
          .then(() => {
            // 删除选中的优惠券
            if (this.chosenCoupon !== -1) {
              const couponId = this.coupons[this.chosenCoupon].id;
              http.get(`coupon/delete/${couponId}`)
                  .then(response => {
                    if (response.statusCode === '200') {
                      Toast.success("优惠券已删除");
                    } else {
                      Toast.fail("删除优惠券失败：" + response.message);
                    }
                  })
                  .catch(error => {
                    console.error("删除优惠券失败:", error);
                    Toast.fail("删除优惠券失败");
                  });
            }
            const orderList = {
              username: JSON.parse(sessionStorage.getItem('username')),
              orderDataList: this.orderItems.map(item => ({
                cartId: item.cartId,
                productName: item.title,
                skuDescription: item.description,
                itemPrice: item.itemPrice,
                skuQuantity: item.skuQuantity,
                productId: item.productId,
                stockNum: item.max,
              })),
              status:"0",
              addressId:this.AddressId,
              couponDiscount: this.couponDiscount * 100 // 转换为整数值（分）
            };

            // 发送请求到后端
            http.post('/order/createOrder', orderList)
                .then(response => {
                  if (response.statusCode === '200') {
                    Toast.success("订单还未支付"+response.data);
                    this.$router.go(-1); // 返回上一页
                  } else {
                    Toast.fail("订单创建失败：" + response.message);
                  }
                })
                .catch(error => {
                  console.error("创建订单失败:", error);
                  Toast.fail("订单创建失败");
                });
          })
          .catch(() => {
            // 用户取消操作
          });
    },
    onSubmit() {
      this.showConfirmDialog();
    },
    showConfirmDialog() {
      Dialog.confirm({
        title: '确认付款',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        allowHtml: true // 允许在对话框中使用 HTML
      })
          .then(() => {
            // 删除选中的优惠券
            if (this.chosenCoupon !== -1) {
              const couponId = this.coupons[this.chosenCoupon].id;
              http.get(`coupon/delete/${couponId}`)
                  .then(response => {
                    if (response.statusCode === '200') {
                      Toast.success("优惠券已删除");
                    } else {
                      Toast.fail("删除优惠券失败：" + response.message);
                    }
                  })
                  .catch(error => {
                    console.error("删除优惠券失败:", error);
                    Toast.fail("删除优惠券失败");
                  });
            }
            const orderList = {
              username: JSON.parse(sessionStorage.getItem('username')),
              orderDataList: this.orderItems.map(item => ({
                cartId: item.cartId,
                productName: item.title,
                skuDescription: item.description,
                itemPrice: item.itemPrice,
                skuQuantity: item.skuQuantity,
                productId: item.productId,
                stockNum: item.max,
              })),
              status:"1",
              addressId:this.AddressId,
              couponDiscount: this.couponDiscount * 100 // 转换为整数值（分）
            };
            console.log(orderList)
            http.post('/order/createOrder', orderList)
                .then(response => {
                  if (response.statusCode === '200') {
                    Toast.success("订单支付成功"+response.data);
                    this.$router.push('/MyView'); // 返回上一页
                  } else {
                    Toast.fail("订单支付失败：" + response.message);
                  }
                })
                .catch(error => {
                  console.error("订单支付失败:", error);
                  Toast.fail("订单支付失败");
                });
          })
          .catch(() => {
            const orderList = {
              username: JSON.parse(sessionStorage.getItem('username')),
              orderDataList: this.orderItems.map(item => ({
                cartId: item.cartId,
                productName: item.title,
                skuDescription: item.description,
                itemPrice: item.itemPrice,
                skuQuantity: item.skuQuantity,
                productId: item.productId,
                stockNum: item.max
              })),
              status:"0",
              addressId:this.AddressId,
              couponDiscount: this.couponDiscount * 100
            };
            console.log(orderList);
            http.post('/order/createOrder', orderList)
                .then(response => {
                  if (response.statusCode === '200') {
                    Toast.success("订单还未支付"+response.data);
                  } else {
                    Toast.fail("订单支付失败：" + response.message);
                  }
                })
                .catch(error => {
                  console.error("订单支付失败:", error);
                  Toast.fail("订单支付失败");
                });
            console.log("订单信息:",orderList);
          });
    },
    showAddressModal() {
      this.showModal = true;
    },
    showDeliveryModal() {
      this.showDeliveryModalPopup = true;
    },
    fetchDefaultAddress() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        http.get(`/address/${storedUser}`)
            .then(response => {
              const addresses = response.data;
              if (addresses && addresses.length > 0) {
                const defaultAddress = addresses.find(item => item.moRen === 1);
                if (defaultAddress) {
                  this.AddressId = defaultAddress.addressId;
                  this.chosenAddress = {
                    region: `${defaultAddress.province} ${defaultAddress.city} ${defaultAddress.district}`,
                    addressLine: defaultAddress.addressLine,
                    name: defaultAddress.name,
                    contact: defaultAddress.contact,
                    isDefault: true
                  };
                }
              }
            })
            .catch(error => {
              console.error("获取地址信息出错:", error);
            });
      } else {
        console.error("没有用户登录");
      }
    },
    updateChosenAddressFromRoute() {
      const chosenAddressId = this.$route.query.chosenAddressId;
      if (chosenAddressId) {
        this.fetchAddressById(chosenAddressId);
      }
    },
    fetchAddressById(addressId) {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        http.get(`/address/id/${addressId}`)
            .then(response => {
              const address = response.data;
              if (address) {
                this.AddressId = addressId;
                this.chosenAddress = {
                  region: `${address.province} ${address.city} ${address.district}`,
                  addressLine: address.addressLine,
                  name: address.name,
                  contact: address.contact,
                  isDefault: address.moRen === 1
                };
                this.showModal = false;
              }
            })
            .catch(error => {
              console.error("通过ID获取地址信息出错:", error);
            });
      } else {
        console.error("没有用户登录");
      }
    },
    selectAddressById(addressId) {
      this.fetchAddressById(addressId);
    },
    selectDeliveryMethod(method) {
      this.deliveryMethod = method;
      this.showDeliveryModalPopup = false;
    }
  }
};
</script>

<style scoped>
.regulatory-page {
  background-color: #F6F7F9;
  padding-bottom: 100px;
}

.return {
  background-color: #FAEAEA;
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.back {
  position: absolute;
  left: 10px;
  text-decoration: none;
}

.title {
  display: flex;
  align-items: center;
}

.text {
  margin: 0;
  color: #000000;
  font-size: 16px;
}

.address-display {
  background-color: #ffffff;
  padding: 10px;
  margin: 10px;
  border-radius: 10px;
  cursor: pointer;
}

.address-display p {
  margin-left: 10px;
  line-height: 1.5;
}

.first-line {
  font-size: 14px;
  padding-bottom: 5px;
}

.second-line {
  font-weight: bold;
  font-size: 17px;
  padding-bottom: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.third-line {
  font-size: 14px;
}

.default-tag {
  background-color: #faeaea;
  color: #e53e3e;
  padding: 2px 5px;
  margin-left: 10px;
  font-size: 12px;
  border-radius: 3px;
}

.arrow-right {
  margin-left: auto;
}
.van-card-full
{
  background-color: #ffffff;
}
.info-display
{
  margin-left: 10px;
  margin-right: 10px;
  background-color: #ffffff;
  padding-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
}
.delivery-display
{
}
.common-display
{
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10px;
  padding-right: 10px;
  cursor: pointer;
  padding-top: 15px;
}
.left-text
{
  color: #999987;
  display: flex;
  align-items: center;
}
.right-text
{
  font-size: 14px;
  display: flex;
  align-items: center;
}
.price-display
{
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  background-color: #ffffff;
  padding-bottom: 10px;
  border-radius: 10px;
  overflow: hidden;
}
.divider {
  height: 1px;
  background-color: #f5f5f5;
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  border-radius: 10px;
}
.total-account
{
  padding-top: 10px;
  text-align: right;
  padding-right: 10px;
}
.total-price
{
  font-size:20px;
  color: #FA6408;
}
.coupons-display
{
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  background-color: #ffffff;
  padding-bottom: 15px;
  border-radius: 10px;
  overflow: hidden;
}
.pay-display
{
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  background-color: #ffffff;
  padding-bottom: 15px;
  border-radius: 10px;
  overflow: hidden;
}
.pay-text
{
  font-size: 14px;
  display: flex;
  align-items: center;
}
.pay-icon
{
  padding-right: 5px;
}
.delivery-options {
  display: flex;
  flex-direction: column;
  padding: 20px;
}
.delivery-option {
  padding: 15px;
  text-align: center;
  cursor: pointer;
}
</style>

